package com.meisupic.copyright.support.security;

import com.meisupic.copyright.util.StringUtil;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * creation wuxun
 *
 * @version V1.0
 * @Description: 验证用户名密码正确后，生成一个token，并将token返回给客户端 该类继承自UsernamePasswordAuthenticationFilter，重写了其中的2个方法
 * attemptAuthentication ：接收并解析用户凭证。 successfulAuthentication ：用户成功登录后，这个方法会被调用，我们在这个方法里生成token。
 * @date 2018/1/13 15:16
 */
public class UserIdLoginFilter extends AbstractAuthenticationProcessingFilter {


  private RememberMeServices rememberMeServices = new NullRememberMeServices();


  public UserIdLoginFilter() {
    super(new AntPathRequestMatcher("/token"));
  }

  // 接收并解析用户凭证
  @Override
  public Authentication attemptAuthentication(HttpServletRequest req,
      HttpServletResponse res) throws AuthenticationException {
    String userId = req.getParameter("userId");
    String userCaid = req.getParameter("caid");
    UserIdAuthenticationToken authenticationToken = new UserIdAuthenticationToken(userId,
        userCaid);
    Authentication authentication = this.getAuthenticationManager()
        .authenticate(authenticationToken);
    return authentication;
  }

  protected void successfulAuthentication(HttpServletRequest request,
      HttpServletResponse response, FilterChain chain, Authentication authResult)
      throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
      logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
          + authResult);
    }

    SecurityContextHolder.getContext().setAuthentication(authResult);

    rememberMeServices.loginSuccess(request, response, authResult);

    // Fire event
    if (this.eventPublisher != null) {
      eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
          authResult, this.getClass()));
    }

    String original = request.getParameter("original");
    String thumbnail = request.getParameter("thumbnail");
    String width = request.getParameter("width");
    String height = request.getParameter("height");
    String publishDate = request.getParameter("publishDate");
    if (StringUtil.isEmpty(original) && StringUtil.isEmpty(thumbnail) && StringUtil.isEmpty(width)
        && StringUtil.isEmpty(height) && StringUtil.isEmpty(publishDate)) {
      response.sendRedirect("copyright/register/edit");
    }else{
      String redirectUrl = String.format("copyright/register/huaban?original=%s&thumbnail=%s&width=%s&height=%s&publishDate=%s",original,thumbnail,width,height,publishDate);
      response.sendRedirect(redirectUrl);
    }

  }
}
